#!/bin/bash

TOP=`pwd`
RESULT_DIR=${TOP}/output
AFBOOT_DIR=${TOP}/bootable/afboot-stm32
KERNEL_DIR=${TOP}/kernel/linux-4.11.y
ROOTFS_DIR=${TOP}/rootfs/initramfs
HAL_DIR=${TOP}/rootfs/hal

function build_afboot()
{
	echo ""
	echo "=============================================="
	echo "build afboot"
	echo "=============================================="

	cd $AFBOOT_DIR
	make clean
	make

	mkdir -p $RESULT_DIR
	cp $AFBOOT_DIR/stm32f429i-disco.bin ${RESULT_DIR}/stm32f429i-disco-afboot.bin
	cd ${TOP}
	echo "---------- End of build afboot"
	echo "=============================================="
	echo "     "
	echo "afboot address: 0x08000000"
}

function build_kernel()
{
	echo ""
	echo "=============================================="
	echo "build kernel"
	echo "=============================================="

	cd $KERNEL_DIR
	make ARCH=arm CROSS_COMPILE=arm-none-eabi- INITRAMFS_SOURCE=$TOP/output/rootfs.cpio stm32_defconfig
	make ARCH=arm CROSS_COMPILE=arm-none-eabi-
	#make ARCH=arm CROSS_COMPILE=arm-none-eabi- modules

	cp $KERNEL_DIR/arch/arm/boot/dts/stm32f429-disco.dtb $RESULT_DIR/stm32f429-disco.dtb.bin
	cp $KERNEL_DIR/arch/arm/boot/xipImage $RESULT_DIR/xipImage.bin
	echo "---------- End of build kernel"
	echo "     "
	echo "dtb address:    0x08004000"
	echo "kernel address: 0x08008000"
}

function make_rootfs()
{
	echo ""
	echo "=============================================="
	echo "start make rootfs(initramfs)"
	echo "=============================================="

	cd ${TOP}
	rm -rf $RESULT_DIR/initramfs
	mkdir -p $RESULT_DIR/initramfs
	cp -a $ROOTFS_DIR $RESULT_DIR
	echo "make hal"
	cd $HAL_DIR
	export APP_CROSS_COMPILER=arm-linux-
	export APP_INSTALL_PATH=$RESULT_DIR/initramfs/bin
	make

	cd ${TOP}
	fakeroot -- ${TOP}/build/build_sh/fakeroot.sh
	echo "---------- End of make_system"
	cp $RESULT_DIR/rootfs.cpio ${TOP}/rootfs
	echo "rootfs(initramfs): rootfs/rootfs.cpio is ready"
}

function build_clean()
{
	echo "Clean Kernel ..."
	cd $KERNEL_DIR
	make clean
	cd ${TOP}

	echo "Clean afboot ..."
	cd $AFBOOT_DIR
	make clean
	cd ${TOP}

	echo "Clean Hal ..."
	cd $HAL_DIR
	make clean
	cd ${TOP}

	rm -rf ${RESULT_DIR}
}

function build_usage()
{
	echo "Usage: $0 <type>"
	echo "       type:"
	echo "            afboot"
	echo "            kernel"
	echo "            rootfs"
	echo "            all"
	echo "            clean"
	echo "            "
	echo "            "
}

if [ $# != 1 ] ; then 
	build_usage
	exit 1; 
fi 


if [ "$1" = "afboot" ]
then
	build_afboot
elif [ "$1" = "kernel" ]
then
	build_kernel
elif [ "$1" = "rootfs" ]
then
	make_rootfs
elif [ "$1" = "all" ]
then
	build_afboot
	make_rootfs
	build_kernel

	echo "     "
	echo "download:"
	echo "afboot address: 0x08000000"
	echo "dtb address:    0x08004000"
	echo "kernel address: 0x08008000"
	echo "     "
elif [ "$1" = "clean" ]
then

	build_clean
else
	build_usage
fi

